#include "promotionmanagerwindow.h"
#include <QMessageBox>
#include <QDebug>
#include <QApplication>
#include <QSqlError>
#include <QDateTime>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QScopedValueRollback>
#include <QTimer>
#include <QDateTime>

PromotionManagerWindow::PromotionManagerWindow(QSqlDatabase db, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PromotionManagerWindow),
    m_db(db),
    m_activityModel(nullptr),
    m_editingActivityId(-1),
    m_isProcessing(false)
{
    ui->setupUi(this);
    setWindowTitle("促销活动管理");

    if (!m_db.isOpen()) {
        qDebug() << "数据库连接无效！";
        QMessageBox::critical(this, "错误", "数据库连接失败，请重试！");
        return;
    }

    // 重新连接信号槽（确保只连接一次，若 ui 初始化无默认连接可省略 disconnect ）
 //   connect(ui->pushButtonEdit, &QPushButton::clicked, this, &PromotionManagerWindow::on_pushButtonEdit_clicked);
//    connect(ui->pushButtonDelete, &QPushButton::clicked, this, &PromotionManagerWindow::on_pushButtonDelete_clicked);
 //   connect(ui->pushButtonLoad, &QPushButton::clicked, this, &PromotionManagerWindow::on_pushButtonLoad_clicked);

    loadProductsToCombo();
    loadActivitiesToTable();

    qDebug() << "PromotionManagerWindow 初始化完成";
}

PromotionManagerWindow::~PromotionManagerWindow()
{
    delete ui;
    if (m_activityModel) {
        delete m_activityModel;
    }
}

void PromotionManagerWindow::loadProductsToCombo()
{
    QSqlQuery query(m_db);
    if (!query.exec("SELECT name FROM products")) {
        qDebug() << "加载商品失败:" << query.lastError().text();
        QMessageBox::warning(this, "错误", "加载商品列表失败: " + query.lastError().text());
        return;
    }

    ui->comboBoxFlowers->clear();
    ui->comboBoxFlowers->addItem("所有花卉", "all");

    while (query.next()) {
        QString productName = query.value(0).toString();
        ui->comboBoxFlowers->addItem(productName, productName);
    }

    qDebug() << "商品列表加载完成，共" << ui->comboBoxFlowers->count() << "项";
}

void PromotionManagerWindow::loadActivitiesToTable()
{
    if (m_activityModel) {
        delete m_activityModel;
        m_activityModel = nullptr;
    }

    m_activityModel = new QSqlQueryModel(this);
    QString sql = R"(
        SELECT
            activity_id,
            name,
            type,
            discount_rate,
            condition,
            CASE WHEN apply_to = 'all' THEN '所有花卉' ELSE apply_to END AS apply_to_display,
            start_time,
            end_time,
            status,
            description
        FROM Activities
    )";
    m_activityModel->setQuery(sql, m_db);

    if (m_activityModel->lastError().isValid()) {
        qDebug() << "加载活动列表失败:" << m_activityModel->lastError().text();
        QMessageBox::warning(this, "错误", "加载活动列表失败: " + m_activityModel->lastError().text());
        return;
    }

    m_activityModel->setHeaderData(0, Qt::Horizontal, "ID");
    m_activityModel->setHeaderData(1, Qt::Horizontal, "活动名称");
    m_activityModel->setHeaderData(2, Qt::Horizontal, "类型");
    m_activityModel->setHeaderData(3, Qt::Horizontal, "折扣率");
    m_activityModel->setHeaderData(4, Qt::Horizontal, "条件");
    m_activityModel->setHeaderData(5, Qt::Horizontal, "适用花卉");
    m_activityModel->setHeaderData(6, Qt::Horizontal, "开始时间");
    m_activityModel->setHeaderData(7, Qt::Horizontal, "结束时间");
    m_activityModel->setHeaderData(8, Qt::Horizontal, "状态");
    m_activityModel->setHeaderData(9, Qt::Horizontal, "描述");

    ui->tableView->setModel(m_activityModel);
    ui->tableView->resizeColumnsToContents();
    ui->tableView->clearSelection();

    qDebug() << "活动列表加载完成，共" << m_activityModel->rowCount() << "条记录";
}

void PromotionManagerWindow::on_pushButtonCreate_clicked()
{
    if (m_isProcessing) return;
    QScopedValueRollback<bool> rollback(m_isProcessing);
    m_isProcessing = true;

    QString name = ui->lineEditName->text().trimmed();
    QString desc = ui->textEdit->toPlainText().trimmed();
    QDate start = ui->dateEditStart->date();
    QDate end = ui->dateEditEnd->date();
    QString flower = ui->comboBoxFlowers->currentData().toString();
    double discount = ui->doubleSpinBox->value();

    if (name.isEmpty() || desc.isEmpty() || start.isNull() || end.isNull()) {
        QMessageBox::warning(this, "警告", "请填写所有必填字段！");
        return;
    }
    if (start > end) {
        QMessageBox::warning(this, "警告", "开始日期不能晚于结束日期！");
        return;
    }

    if (m_editingActivityId != -1) {
        QSqlQuery query(m_db);
        query.prepare("UPDATE Activities "
                      "SET name=:name, description=:desc, start_time=:start, end_time=:end, apply_to=:flower, discount_rate=:discount "
                      "WHERE activity_id=:id");
        query.bindValue(":name", name);
        query.bindValue(":desc", desc);
        query.bindValue(":start", start.toString("yyyy-MM-dd"));
        query.bindValue(":end", end.toString("yyyy-MM-dd"));
        query.bindValue(":flower", flower);
        query.bindValue(":discount", discount);
        query.bindValue(":id", m_editingActivityId);

        if (query.exec()) {
            QMessageBox::information(this, "成功", "活动修改成功！");
            loadActivitiesToTable();
            on_pushButtonClear_clicked();
            m_editingActivityId = -1;
        } else {
            qDebug() << "修改失败:" << query.lastError().text();
            QMessageBox::warning(this, "错误", "活动修改失败！");
        }
    } else {
        QString condition = (flower == "all") ? "all" : "category";

        QSqlQuery query(m_db);
        query.prepare("INSERT INTO Activities (name, type, discount_rate, condition, apply_to, start_time, end_time, status, description) "
                      "VALUES (:name, 'flash_sale', :discount, :condition, :flower, :start, :end, 'upcoming', :desc)");
        query.bindValue(":name", name);
        query.bindValue(":discount", discount);
        query.bindValue(":condition", condition);
        query.bindValue(":flower", flower);
        query.bindValue(":start", start.toString("yyyy-MM-dd"));
        query.bindValue(":end", end.toString("yyyy-MM-dd"));
        query.bindValue(":desc", desc);

        if (query.exec()) {
            QMessageBox::information(this, "成功", "活动创建成功！");
            loadActivitiesToTable();
            on_pushButtonClear_clicked();
        } else {
            qDebug() << "创建失败:" << query.lastError().text();
            QMessageBox::warning(this, "错误", "活动创建失败！");
        }
    }
}

void PromotionManagerWindow::on_pushButtonClear_clicked()
{
    ui->lineEditName->clear();
    ui->textEdit->clear();
    ui->dateEditStart->setDate(QDate::currentDate());
    ui->dateEditEnd->setDate(QDate::currentDate());
    ui->comboBoxFlowers->setCurrentIndex(0);
    ui->doubleSpinBox->setValue(0.00);

    m_editingActivityId = -1;
}

void PromotionManagerWindow::on_pushButtonReturn_clicked()
{
    emit returnRequested();
    this->hide();
}

void PromotionManagerWindow::on_pushButtonDelete_clicked()
{
    if (m_isProcessing) return;
    QScopedValueRollback<bool> rollback(m_isProcessing);
    m_isProcessing = true;

    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择要删除的活动！");
        return;
    }
    if (selected.size() > 1) {
        QMessageBox::warning(this, "警告", "暂不支持批量删除，请选一行！");
        return;
    }

    int activityId = m_activityModel->data(m_activityModel->index(selected.first().row(), 0)).toInt();

    if (QMessageBox::question(this, "确认", "确定删除选中活动？") == QMessageBox::Yes) {
        QSqlQuery query(m_db);
        query.prepare("DELETE FROM Activities WHERE activity_id=:id");
        query.bindValue(":id", activityId);

        if (query.exec()) {
            QMessageBox::information(this, "成功", "活动删除成功！");
            loadActivitiesToTable();
        } else {
            qDebug() << "删除失败:" << query.lastError().text();
            QMessageBox::warning(this, "错误", "活动删除失败！");
        }
    }

}

//计算商品价格的辅助函数
void PromotionManagerWindow::on_pushButtonEdit_clicked()
{
    if (m_isProcessing) return;
    QScopedValueRollback<bool> rollback(m_isProcessing);
    m_isProcessing = true;

    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择要修改的活动！");
        return;
    }
    if (selected.size() > 1) {
        QMessageBox::warning(this, "警告", "暂不支持批量修改，请选一行！");
        return;
    }

    QSqlRecord record = m_activityModel->record(selected.first().row());
    ui->lineEditName->setText(record.value("name").toString());
    ui->textEdit->setText(record.value("description").toString());
    ui->dateEditStart->setDate(QDate::fromString(record.value("start_time").toString(), "yyyy-MM-dd"));
    ui->dateEditEnd->setDate(QDate::fromString(record.value("end_time").toString(), "yyyy-MM-dd"));

    QString applyTo = record.value("apply_to_display").toString();
    if (applyTo == "所有花卉") {
        ui->comboBoxFlowers->setCurrentIndex(0);
    } else {
        int index = ui->comboBoxFlowers->findData(applyTo);
        if (index != -1) {
            ui->comboBoxFlowers->setCurrentIndex(index);
        }
    }

    ui->doubleSpinBox->setValue(record.value("discount_rate").toDouble());

    m_editingActivityId = record.value("activity_id").toInt();
    QMessageBox::information(this, "提示", "修改后点「创建促销活动」保存！");
}

void PromotionManagerWindow::on_pushButtonLoad_clicked()
{
    if (m_isProcessing) return;
    QScopedValueRollback<bool> rollback(m_isProcessing);
    m_isProcessing = true;

    loadActivitiesToTable();
    QMessageBox::information(this, "提示", "活动列表已刷新！");
}

#include <QDateTime>

double PromotionManagerWindow::getProductPrice(const QString& productName)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();

    // 查询当前是否有针对该商品的促销活动
    QSqlQuery query(m_db);
    query.prepare("SELECT discount_rate, start_time, end_time "
                  "FROM Activities "
                  "WHERE (apply_to = :product OR apply_to = 'all') "
                  "AND start_time <= :currentDateTime "
                  "AND end_time >= :currentDateTime");
    query.bindValue(":product", productName);
    query.bindValue(":currentDateTime", currentDateTime.toString("yyyy-MM-dd"));

    if (query.exec() && query.next()) {
        double discountRate = query.value("discount_rate").toDouble();

        // 查询商品的原价
        QSqlQuery priceQuery(m_db);
        priceQuery.prepare("SELECT price FROM products WHERE name = :product");
        priceQuery.bindValue(":product", productName);

        if (priceQuery.exec() && priceQuery.next()) {
            double originalPrice = priceQuery.value("price").toDouble();
            return originalPrice * discountRate;
        }
    }

    // 如果没有促销活动，返回商品的原价
    QSqlQuery priceQuery(m_db);
    priceQuery.prepare("SELECT price FROM products WHERE name = :product");
    priceQuery.bindValue(":product", productName);

    if (priceQuery.exec() && priceQuery.next()) {
        return priceQuery.value("price").toDouble();
    }

    return 0.0;
}
